/**  
 * 缓存数据优化  
 * import storage from '@/storage'
 * 使用方法 【  
 *     一、设置缓存  
 *         string    storage.set('k', 'string你好啊');  
 *         json      storage.set('k', { "b": "3" }, 2);  
 *         array     storage.set('k', [1, 2, 3]);  
 *         boolean   storage.set('k', true);  
 *     二、读取缓存  
 *         默认值    storage.get('k')  
 *         string    storage.get('k', '你好')  
 *         json      storage.get('k', { "a": "1" })  
 *     三、移除/清理    
 *         移除: storage.remove('k');  
 *         清理：storage.clear();   
 * 】  
 * @type {String}  
 */

const postfix = '_expiry' // 缓存有效期后缀   


/**
 *  设置缓存
 * @param key 
 * @param value 
 * @param seconds 
 */

function set(key:string, value:any): void;
function set(key:string, value:any, seconds?: number): void{
  uni.setStorageSync(key, value)
  setExpireKey(key, seconds)
}

/**
 *  设置缓存
 * @param key  
 * @param value 
 */
function setJson(key:string, value:any): void;
function setJson(key:string, value:any, seconds?: number): void{
  uni.setStorageSync(key, JSON.stringify(value))
  setExpireKey(key, seconds)
}

/**
 *  设置过期key值
 * @param key  
 * @param seconds 
 */
function setExpireKey(key:string, seconds?: number){
  if (seconds && seconds > 0) {
    let timestamp = Date.parse(new Date() + '')
    timestamp = timestamp / 1000 + seconds
    uni.setStorageSync(key + postfix, timestamp + '')
  } else {
    uni.removeStorageSync(key + postfix)
  }
}

/**
 *  获取缓存 
 * @param key 
 * @param value 
 * @param seconds 
 * @returns 
 */
const get = (key:string, defaultValue: any = null) => {
  const deadtime = parseInt(uni.getStorageSync(key + postfix))
  if (deadtime) {
    if (deadtime < Date.parse(new Date() + '') / 1000) {
      remove(key)                                
      return defaultValue
    }
  }
  const res = uni.getStorageSync(key)
  if (res) {
    return res
  }
  return defaultValue
}

/**
 *  获取缓存
 * @param key 
 * @param defaultValue 
 * @returns 
 */
const getJson =  (key:string, defaultValue: any = null) => {
   return JSON.parse(get(key, defaultValue) || '{}')
}



/**
 * 删除指定缓存
 * @param {Object} key
 */
const remove = (key: string) => {
  uni.removeStorageSync(key)
  uni.removeStorageSync(key + postfix)
}

/**
 *  清理所有缓存 
 */
const clear = () => {
  uni.clearStorage()
}



export default {
  set,
  setJson,
  get,
  getJson,
  remove,
  clear
}
